package com.cloud.pole.weixin.service.impl;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloud.pole.common.constant.CacheConstant;
import com.cloud.pole.common.constant.CommonConstants;
import com.cloud.pole.common.exception.BaseException;
import com.cloud.pole.common.util.DateUtils;
import com.cloud.pole.weixin.biz.WxAppBiz;
import com.cloud.pole.weixin.biz.WxReplyConfigBiz;
import com.cloud.pole.weixin.biz.WxReplyMsgBiz;
import com.cloud.pole.weixin.biz.WxUserBiz;
import com.cloud.pole.weixin.model.entity.WxApp;
import com.cloud.pole.weixin.model.entity.WxReplyConfig;
import com.cloud.pole.weixin.model.entity.WxReplyMsg;
import com.cloud.pole.weixin.model.entity.WxUser;
import com.cloud.pole.weixin.service.WechatApiService;
import com.cloud.pole.weixin.service.WxMenuService;
import com.cloud.pole.weixin.service.WxUserService;
import com.cloud.pole.weixin.util.wechat.CommonRequest;
import com.cloud.pole.weixin.wechat.CommonService;
import com.cloud.pole.weixin.wechat.domain.AccessToken;
import com.cloud.pole.weixin.wechat.domain.BaseRespMsg;
import com.cloud.pole.weixin.wechat.domain.UserInfo;
import com.cloud.pole.weixin.wechat.message.Msg;
import com.cloud.pole.weixin.wechat.message.Msg4Image;
import com.cloud.pole.weixin.wechat.message.Msg4Text;
import lombok.extern.slf4j.Slf4j;
import com.ace.cache.api.CacheAPI;

/*
*2019年4月24日
*cloud-weixin
*author:frank-chen
*/
@Slf4j
@Service
public class WechatApiServiceImpl implements WechatApiService {
	
	@Autowired
	private WxAppBiz wxAppBiz;
	@Autowired
	private WxUserBiz wxUserBiz;
	@Autowired
	private WxUserService wxUserService;
	@Autowired
    private CacheAPI cacheAPI;
	@Autowired
	private WxReplyConfigBiz replyConfigBiz;
	@Autowired
	private WxReplyMsgBiz replyMsgBiz;
	@Autowired
	private WxMenuService menuService;
	
	@Override
	public WxUser getWxUserInfoByCode(String code, Integer wxAppId) throws Exception {
		// TODO Auto-generated method stub
		WxApp wxApp = wxAppBiz.selectByPrimaryKey(wxAppId);
		if(wxApp == null || wxApp.getAppStatus().intValue() !=  WxApp.APP_STATUS_OK) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "wxAppId错误");
		}
		//网页授权access_token和普通access_token的区别
		String getAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ wxApp.getAppId()+"&secret="+wxApp.getAppSecret()+"&code="+code+"&grant_type=authorization_code";
		String accessTokenResult = CommonRequest.doGet(getAccessTokenUrl);
		log.info("通过code换取网页授权access_token,结果："+accessTokenResult);
		JSONObject accessJson = JSONObject.parseObject(accessTokenResult);
		if(accessJson.containsKey("errcode")){
			String errcode = accessJson.getString("errcode");
			String errmsg = accessJson.getString("errmsg");
			log.error("appId[" + wxApp.getAppId() + "] errcode[" + errcode + "] errmsg[" + errmsg + "]");
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, errcode + ":" + errmsg);
		}
		if(!accessJson.containsKey("openid")){
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "获取openid错误");
		}
		if(!accessJson.containsKey("access_token")){
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "获取access_token错误");
		}
		String accessToken = accessJson.getString("access_token");
		String openid  	= accessJson.getString("openid");
		String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
		String userInfoResult = CommonRequest.doGet(getUserInfoUrl);
		JSONObject userInfoJson = JSONObject.parseObject(userInfoResult);
		String nickname = "", province = "", city = "", country = "", headimgurl = "", unionid = "";
		int sex = 0;
		if(userInfoJson.containsKey("nickname")){
			nickname = userInfoJson.getString("nickname");
		}
		if(userInfoJson.containsKey("province")){
			province = userInfoJson.getString("province");
		}
		if(userInfoJson.containsKey("city")){
			city = userInfoJson.getString("city");
		}
		if(userInfoJson.containsKey("country")){
			country = userInfoJson.getString("country");
		}
		if(userInfoJson.containsKey("headimgurl")){
			headimgurl = userInfoJson.getString("headimgurl");
		}
		if(userInfoJson.containsKey("sex")){
			sex = userInfoJson.getIntValue("sex");
		}
		if(userInfoJson.containsKey("unionid")){
			unionid = userInfoJson.getString("unionid");
		}
		WxUser wxUser = wxUserBiz.selectByOpenId(openid);
		if(wxUser == null) {
			wxUser = new WxUser();
			wxUser.setAppId(wxApp.getAppId());
			wxUser.setAvatarUrl(headimgurl);
			wxUser.setCity(city);
			wxUser.setCountry(country);
			wxUser.setCreateTime(new Date());
			wxUser.setGender(sex);
			wxUser.setNickName(nickname);
			wxUser.setOpenId(openid);
			wxUser.setProvince(province);
			wxUser.setUnionId(unionid);
			wxUser.setWxAppId(wxAppId);
			wxUser.setSubscribeStatus(WxUser.SUBSCRIBESTATUS_DEFAULT);
			wxUserBiz.insert(wxUser);
		}
		else {
			wxUser.setAvatarUrl(headimgurl);
			wxUser.setCity(city);
			wxUser.setCountry(country);
			wxUser.setGender(sex);
			wxUser.setNickName(nickname);
			wxUser.setProvince(province);
			wxUser.setUnionId(unionid);
			wxUser.setWxAppId(wxAppId);
			wxUser.setUpdateTime(new Date());
			wxUserBiz.updateByPrimaryKey(wxUser);
		}
		return wxUser;
	}
	
	@Override
	public AccessToken getAccessToken(WxApp wxApp) throws Exception {
		String key =  CacheConstant.SERVICE_WEIXIN_ACCESS_TOKEN_KEY + ":"  + wxApp.getAppId();
		String json = cacheAPI.get(key);
	    Date now = new Date();
	    AccessToken accessToken = null;
		if(!StringUtils.isEmpty(json)) {
		     accessToken = JSON.parseObject(json, AccessToken.class);
			 if(accessToken == null || DateUtils.minusSeconds(accessToken.getCreateTime(), now, true) > (accessToken.getExpires_in() - 30 * 60)) {
				 if(accessToken != null) {
					 cacheAPI.remove(key);
				 }
				 accessToken = CommonService.getAccessToken(cacheAPI, wxApp.getAppId(), wxApp.getAppSecret());
			 }
		}
		else {
			 accessToken = CommonService.getAccessToken(cacheAPI, wxApp.getAppId(), wxApp.getAppSecret());
		}
	    return accessToken;
	}

	@Override
	public void subscribeWxUser(String openId, String originalId) throws Exception {
		// TODO Auto-generated method stub
	    WxApp wxApp = wxAppBiz.selectByOriginalId(originalId);
		AccessToken accessToken = getAccessToken(wxApp);
	    if(wxApp == null) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "appId错误");
	    }
		UserInfo userInfo = CommonService.getSubscribeUserInfo(openId, accessToken.getAccess_token());
		//保存数据
		wxUserService.modifyWxUser(userInfo, wxApp);
	}
	
	@Override
	public void unSubscribeWxUser(String openId, String originalId) throws Exception {
		//保存数据
		wxUserService.unSubscribeWxUser(openId);
	}

	@Override
	public Msg getReplyMsg(String eventType, String eventKey, String openId, String originalId) throws Exception {
		// TODO Auto-generated method stub
	    WxApp wxApp = wxAppBiz.selectByOriginalId(originalId);
	    if(wxApp == null) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "appId错误");
	    }
	    Msg replyMsg = null;
	    //读取配置
	    WxReplyConfig config  = replyConfigBiz.selectWxReplyConfig(wxApp.getWxAppId(), eventType, eventKey);
	    if(config != null && config.getReplyMsgId() != null) {
	    	WxReplyMsg wxReplyMsg = replyMsgBiz.selectByPrimaryKey(config.getReplyMsgId());
	    	if(wxReplyMsg != null && wxReplyMsg.getMsgStatus() == WxReplyMsg.REPLY_STATUS_OK) {
	    		String msgType = wxReplyMsg.getMsgType();
	    		String content = wxReplyMsg.getMsgContent();
	    		String mediaId = wxReplyMsg.getMediaId();
	    		if(StringUtils.equalsIgnoreCase(msgType, Msg.MSG_TYPE_TEXT) && !StringUtils.isEmpty(content)) {
	    			replyMsg = new Msg4Text();
	    			((Msg4Text) replyMsg).setContent(content);
	    			replyMsg.setFromUserName(originalId);
	    			replyMsg.setToUserName(openId);
	    		}
	    		else if(StringUtils.equalsIgnoreCase(msgType, Msg.MSG_TYPE_IMAGE) && !StringUtils.isEmpty(mediaId)) {
	    			replyMsg = new Msg4Image();
	    			((Msg4Image) replyMsg).setMediaId(mediaId);
	    			replyMsg.setFromUserName(originalId);
	    			replyMsg.setToUserName(openId);
	    		}
	    	}
	    }
		return replyMsg;
	}

	@Override
	public BaseRespMsg createMenu(Integer wxAppId) throws Exception {
		// TODO Auto-generated method stub
		WxApp wxApp = wxAppBiz.selectByPrimaryKey(wxAppId);
		if(wxApp == null || wxApp.getAppStatus().intValue() !=  WxApp.APP_STATUS_OK) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "wxAppId错误");
		}
		AccessToken accessToken = getAccessToken(wxApp);
		String strJson = menuService.getWxMenu(wxAppId);
		log.info(strJson);

		
//		String shareurl = "shop.yunji999.com";
//		String lijigoumai = "shop.yunji999.com";
//		String wodezhongxin = "shop.yunji999.com";
//		String huoquerweima = "KEY_WDBL_HQEWM";             
//		String wodedingdan = "shop.yunji999.com";
//		
//		String shouhoufuwu = "http://mp.weixin.qq.com/s?__biz=MzA5NDM2Mjc1MQ==&mid=207223208&idx=1&sn=dedf9aa3cd5b1eb49d12cb326a124603#rd";	
//		String xszn = "http://mp.weixin.qq.com/s?__biz=MzA5NDM2Mjc1MQ==&mid=207223422&idx=1&sn=b6174c01647b71117d1187b012ad26f5&scene=0#rd";
//		String gsbj = "http://mp.weixin.qq.com/s?__biz=MzA5NDM2Mjc1MQ==&mid=207223409&idx=1&sn=9b0b5b402bb472ac9441a26c2c7c4c69&scene=0#rd";
//		String zssm = "http://mp.weixin.qq.com/s?__biz=MzA5NDM2Mjc1MQ==&mid=207223438&idx=1&sn=b6fbe1e067e19598979fcb385518b535&scene=0#rd";
//		
//		// String s =
//		// "{\"button\":[{\"name\":\"休闲娱乐\",\"sub_button\":[{\"type\":\"click\",\"name\":\"笑话大全\",\"key\":\"m_joke\"},{\"type\":\"click\",\"name\":\"内涵段子\",\"key\":\"m_duanzi\"},{\"type\":\"click\",\"name\":\"爆笑图片\",\"key\":\"m_laughImg\"}]},{\"name\":\"实用工具\",\"sub_button\":[{\"type\":\"click\",\"name\":\"天气查询\",\"key\":\"m_weather\"},{\"type\":\"click\",\"name\":\"公交查询\",\"key\":\"m_bus\"}]},{\"type\":\"click\",\"name\":\"关于企特\",\"key\":\"m_about\"}]}"
//		// ;
//		strJson = "{\"button\":[{\"name\":\"商城首页\",\"type\":\"view\",\"url\":\""+ lijigoumai+ "\"},"+
//				"{\"name\":\"会员中心\",\"sub_button\":["+	
//				"{\"type\":\"click\",\"name\":\"获取二维码\",\"key\":\""+ huoquerweima+ "\"},"+
//				"{\"type\":\"view\",\"name\":\"我的中心\",\"url\":\"" + wodezhongxin+ "\"},"+
//				"{\"type\":\"view\",\"name\":\"我的订单\",\"url\":\""+ wodedingdan+ "\"}]},"+
//				"{\"name\":\"更多帮助\",\"sub_button\":[{\"type\":\"view\",\"name\":\"好文分享\",\"url\":\""+ shareurl + "\"},"+
//				"{\"type\":\"view\",\"name\":\"新手指南\",\"url\":\"" + xszn+ "\"},"+
//				"{\"type\":\"view\",\"name\":\"公司背景\",\"url\":\"" + gsbj+ "\"},"+
//				"{\"type\":\"view\",\"name\":\"招商说明\",\"url\":\""+ zssm + "\"},"+
//				"{\"type\":\"view\",\"name\":\"售后服务\",\"url\":\""+ shouhoufuwu + "\"}]}"+
//				"]}";
		log.info(strJson);
		
		BaseRespMsg respMsg = CommonService.createMenu(accessToken.getAccess_token(), strJson);
		return respMsg;
	}
}
